import os
import time
import threading
import subprocess
from datetime import datetime

# 常量定义
MOUNT_POINT = "/root/mnt"
LOG_DIR = os.path.join(MOUNT_POINT, "log")
LOG_FILE = os.path.join(LOG_DIR, "app.log")
DEVICE = "/dev/sda1"

# 检查并挂载设备
def check_and_mount():
    if not os.path.ismount(MOUNT_POINT):
        print(f"{MOUNT_POINT} is not mounted. Mounting {DEVICE}...")
        os.makedirs(MOUNT_POINT, exist_ok=True)
        subprocess.run(["mount", DEVICE, MOUNT_POINT], check=True)
    else:
        print(f"{DEVICE} is already mounted at {MOUNT_POINT}.")

# 检查并创建日志目录
def check_and_create_log_dir():
    if not os.path.exists(LOG_DIR):
        print(f"Creating log directory at {LOG_DIR}...")
        os.makedirs(LOG_DIR)
    else:
        print(f"Log directory already exists at {LOG_DIR}.")

# 写入日志
def write_log():
    while True:
        # 检查日志文件是否存在，不存在则创建
        if not os.path.exists(LOG_FILE):
            open(LOG_FILE, "w").close()

        # 获取 ifconfig 的输出
        ifconfig_output = subprocess.run(["ifconfig"], capture_output=True, text=True).stdout

        # 将 ifconfig 输出写入日志文件
        with open(LOG_FILE, "a") as f:
            f.write(f"Timestamp: {datetime.now()}\n")
            f.write(ifconfig_output)
            f.write("\n")

        # 每 3 秒执行一次
        time.sleep(3)

# 日志轮转和压缩
def rotate_and_compress_log():
    while True:
        # 获取当前时间并生成新文件名
        current_time = datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
        new_log_file = os.path.join(LOG_DIR, f"app.{current_time}.log")
        compressed_file = f"{new_log_file}.tgz"

        # 重命名日志文件
        if os.path.exists(LOG_FILE):
            os.rename(LOG_FILE, new_log_file)

            # 压缩日志文件
            subprocess.run(["tar", "-czf", compressed_file, new_log_file], check=True)
            os.remove(new_log_file)
            print(f"Log rotated and compressed: {compressed_file}")

        # 清理 48 小时前的压缩文件
        for file in os.listdir(LOG_DIR):
            if file.endswith(".tgz"):
                file_path = os.path.join(LOG_DIR, file)
                file_age = time.time() - os.path.getmtime(file_path)
                if file_age > 48 * 3600:  # 48 小时
                    os.remove(file_path)
                    print(f"Deleted old log file: {file_path}")

        # 每 1 小时执行一次
        time.sleep(3600)

# 主函数
def main():
    # 检查并挂载设备
    check_and_mount()

    # 检查并创建日志目录
    check_and_create_log_dir()

    # 启动日志写入线程
    log_thread = threading.Thread(target=write_log, daemon=True)
    log_thread.start()

    # 启动日志轮转和压缩线程
    rotate_thread = threading.Thread(target=rotate_and_compress_log, daemon=True)
    rotate_thread.start()

    # 主线程保持运行
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("Program terminated.")

if __name__ == "__main__":
    main()